import {
  CloseCircleOutlined,
  EditOutlined,
  ApartmentOutlined,
} from '@ant-design/icons';
import { Button, Col, Form, Input, Progress, Row, Tooltip, message } from 'antd';
import { useEffect, useState } from 'react';
import DrawerKr from './component/DrawerKr';
import KrDetail from './component/KrDetail';
import RelateModal from './component/RelateModal';
const { TextArea } = Input;

import styles from './index.less';
const ProgressItem = (props) => {
  return <Progress percent={props.value ? Number(props.value) : 0}></Progress>;
};

const OkrForm = (props) => {
  const [list, setList] = useState([]); //默认有一个O
  const [id, setId] = useState(0);
  const [visible, setVisible] = useState(false);
  const [currK, setCurrK] = useState();
  const [editObj, setEditObj] = useState({});
  const [selectId, setSelectId] = useState();
  const [relateVisible, setRelateVisible] = useState(false);
  const { isEdit, isDetailFlag, status, jurisdiction, olist, count, isLeader, okrId } = props;

  useEffect(() => {
    if(!isDetailFlag) {
      props.updateList(JSON.parse(JSON.stringify(list)));
    }    
  }, []);
  useEffect(()=>{
    if (isDetailFlag && count > 0) {
      const nums = olist.map((val, index) => {
        return index + 1;
      });
      props.updateList(JSON.parse(JSON.stringify(nums)));
      setList(nums);
      setId(nums.length);
      const lis = olist.map((item, index) => {
        return {
          [`id${index+1}`]: item.id,
          [`ofinalscore${index + 1}`]: item.ofinalscore,
          [`okrDetailPoList${index + 1}`]: item.okrDetailPoList,
          [`oname${index + 1}`]: item.oname,
          [`oprogress${index + 1}`]: item.oprogress,
          [`oscore${index + 1}`]: item.oscore,
          [`oweight${index + 1}`]: item.oweight,
        };
      });
      let objs = {};
      lis.map((item, index) => {
        objs = Object.assign({}, objs, item);
      });
      console.log(objs, '---objs')
      setEditObj(objs);
    } 
  }, [count])

  const add = () => {
    if(list.length >= 5){
      message.warning('每个OKR建议最多5个O，请合理分配')
      return;
    }
    let newId = id + 1;
    list.push(newId);
    setId(newId);
    setList(JSON.parse(JSON.stringify(list)));
    props.updateList(JSON.parse(JSON.stringify(list)));
  };
  const deleteList = (k) => {
    const newlist = list.filter((v) => v !== k);
    setList(JSON.parse(JSON.stringify(newlist)));
    props.updateList(JSON.parse(JSON.stringify(newlist)));
  };
  const editKrList = (k) => {
    setVisible(true);
    setCurrK(k);
  };
  const updateKrList = (lists) => {
    const oprocess = lists.map(item => item.krprocess).reduce((prev, next)=> Number(prev) + Number(next) ) / lists.length;
    const oscore = lists.map(item => item.krscore).reduce((prev, next)=> Number(prev) + Number(next) ) / lists.length;
    const ofinalscore = lists.map(item => item.krendscore).reduce((prev, next)=> Number(prev) + Number(next) ) / lists.length;
    props.form.setFieldsValue({ [`okrDetailPoList${currK}`]: lists, [`oprocess${currK}`]: oprocess, [`oscore${currK}`]: oscore,  [`ofinalscore${currK}`]: ofinalscore});
  };
  const onCloseVisible = (flag) => {
    setVisible(flag);
  };
  const relateOkr = (k) => {
    const index = list.indexOf(k);
    const currItemId = olist[index].id; // 取当前关联OKR的ID
    setSelectId(currItemId);
    setRelateVisible(true);
  };
  const closeRelateVisible = () => {
    setRelateVisible(false);
  };
  const checkNumber = (_, value) => {
    const regx = /^([1-9][0-9]{0,1}|100)$/;
    if(!regx.test(value)) {
      return Promise.reject(new Error('请输入1-100'));
    } else {
      return Promise.resolve()
    }
  }
  const disabled = (isDetailFlag && !isEdit) || Number(status) != 0;
  const editKrlist = isEdit && (status == '0' || status == '2' || (status == '3' && isLeader))
  const statusFlag3 = status == '2' && isEdit; // 可以评分了


  return (
    <div style={{ width: '90%' }} className={styles.okr_form_wrap}>
      <Form autoComplete="off" form={props.form}>
        {list.length > 0 &&
          list.map((k, index) => {
            return (
              <div key={`${k}`} style={{ position: 'relative' }}>
                {list.length > 1 && status == '0' && (
                  <span
                    className={styles.delete_wrap}
                    onClick={() => {
                      deleteList(k);
                    }}
                  >
                    <CloseCircleOutlined
                      style={{ fontSize: '16px', color: '#1790ff' }}
                    />
                  </span>
                )}
                <Form.Item
                  hidden={true}
                  label={`O${index + 1}`}
                  name={`id${k}`}
                  initialValue={isDetailFlag ? editObj[`id${k}`] : ''}
                >
                
                </Form.Item>
                <Form.Item
                  label={`O${index + 1}`}
                  name={`oname${k}`}
                  rules={[{ required: true, message: '必填' }]}
                  initialValue={isDetailFlag ? editObj[`oname${k}`] : ''}
                >
                  <TextArea
                    autoSize={{ minRows: 1 }}
                    placeholder="请输入O的描述,不能超过300字"
                    maxLength={300}
                    disabled={disabled}
                  />
                </Form.Item>
                <Row gutter={20}>
                  <Col span={4}>
                    <Form.Item
                      label={`权重`}
                      name={`oweight${k}`}
                      rules={[{ required: true, message: '' }, { validator: checkNumber }]}
                      initialValue={isDetailFlag ? editObj[`oweight${k}`] : ''}
                    >
                      <Input placeholder="100" disabled={disabled} maxLength={3} />
                    </Form.Item>
                  </Col>
                  {isDetailFlag && (
                    <Col span={6}>
                      <Form.Item
                        label={`进度`}
                        name={`oprocess${k}`}
                        initialValue={isDetailFlag ? editObj[`oprocess${k}`] : '66'}
                      >
                        <ProgressItem />
                      </Form.Item>
                    </Col>
                  )}
                  {( // 不可修改 Number(status) > 1 && 
                    <Col span={4}>
                      <Form.Item
                        label={`自评分`}
                        name={`oscore${k}`}
                        initialValue={isDetailFlag ? editObj[`oscore${k}`] : ''}
                      >
                        <Input placeholder="0" disabled={!statusFlag3} maxLength={3} />
                      </Form.Item>
                    </Col>
                  )}
                  { ( // 默认与自评分一致 Number(status) > 2 &&
                    <Col span={4}>
                      <Form.Item
                        label={`最终得分`}
                        name={`ofinalscore${k}`}
                        initialValue={isDetailFlag ? editObj[`ofinalscore${k}`] : ''}
                      >
                        <Input placeholder="0" disabled maxLength={3} />
                      </Form.Item>
                    </Col>
                  )}
                  <Col span={4} style={{paddingTop: '5px'}}>
                    {(!okrId || editKrlist) && <Button
                      type="primary"
                      size='small'
                      onClick={() => editKrList(k)}
                      icon={<EditOutlined />}
                    >
                      KR列表
                    </Button>}
                    {/* isEdit && Number(status) == 0 &&  */}
                    {<Tooltip 
                      placement="topLeft"
                      title="关联其他OKR"
                      arrowPointAtCenter
                    >
                      <Button
                        disabled={disabled}
                        size='small'
                        style={{ marginLeft: '5px' }}
                        onClick={() => relateOkr(k)}
                        icon={<ApartmentOutlined />}
                      ></Button>
                    </Tooltip>}
                  </Col>
                </Row>
                <Form.Item
                  name={`okrDetailPoList${k}`}
                  initialValue={isDetailFlag ? editObj[`okrDetailPoList${k}`] : ''}
                >
                  <KrDetail></KrDetail>
                </Form.Item>
              </div>
            );
          })}
        <Button onClick={add} disabled={!isEdit && okrId} type='primary'>Add</Button>
        {visible && (
          <DrawerKr
            k={currK}
            isLeader={isLeader}
            updateKrList={updateKrList}
            isDetailFlag={isDetailFlag}
            isEdit={isEdit}
            status={status}
            visible={visible}
            onCloseVisible={onCloseVisible}
            okrDetailPoList={props.form.getFieldValue([`okrDetailPoList${currK}`])}
          ></DrawerKr>
        )}
        {relateVisible && (
          <RelateModal
            visible={relateVisible}
            id={selectId}
            closeVisible={closeRelateVisible}
          ></RelateModal>
        )}
      </Form>
    </div>
  );
};

export default OkrForm;
